package com.example.ipcserver.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.example.ipc.Book;

import static com.example.ipcserver.constants.Constants.MSG;
import static com.example.ipcserver.constants.Constants.TAG;

public class MessengerService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    private Messenger mMessenger;

    @Override
    public void onCreate() {
        super.onCreate();
        mMessenger = new Messenger(new MessengerHandler());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand() called with: intent = [" + intent + "], flags = [" + flags + "], startId = [" + startId + "]");
        return super.onStartCommand(intent, flags, startId);
    }

    private static class MessengerHandler extends Handler {
        @Override
        public void handleMessage(final Message msg) {
            try {
                Bundle data = msg.getData();
                data.setClassLoader(Book.class.getClassLoader());
                Log.i(TAG, "got msg: " + data.getString(MSG));
                Book book = data.getParcelable("book");

                Log.i(TAG, "got book: " + book);


                final Messenger replyTo = msg.replyTo;
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Bundle bundle = new Bundle();
                            bundle.putString(MSG, "Hello client, i am server , i had received your msg");
                            msg.setData(bundle);
                            replyTo.send(msg);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }, 2 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
